const baseUrl = 'http://localhost:3011';

// 登录
document.getElementById('loginForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  const response = await fetch(`${baseUrl}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });
  const result = await response.json();
  if (response.ok) {
    localStorage.setItem('token', result.token);
    alert('登录成功'); // 提示登录成功
    window.location.href = 'index.html';  // 登录成功后跳转到 index.html
  } else {
    alert(result.error);
  }
});
// 注册
document.getElementById('registerForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  const response = await fetch(`${baseUrl}/auth/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });
  const result = await response.json();
  if (response.ok) {
    alert(result.message);
    window.location.href = 'login.html';
  } else {
    alert(result.error);
  }
});const getTodos = async () => {
  const token = localStorage.getItem('token');
  const response = await fetch(`${baseUrl}/todos`, {
    headers: { Authorization: `Bearer ${token}` }
  });
  const todos = await response.json();
  if (response.ok) {
    displayTodos(todos);
  } else {
    alert('Failed to fetch todos');
  }
};


document.addEventListener('DOMContentLoaded', () => {

  // 获取待办事项
  const getTodos = async () => {
    const token = localStorage.getItem('token');
    const response = await fetch(`${baseUrl}/todos`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    const todos = await response.json();
    if (response.ok) {
      displayTodos(todos);
    } else {
      alert('Failed to fetch todos');
    }
  };

  // 显示待办事项
  const displayTodos = (todos) => {
    const todoList = document.getElementById('todoList');
    todoList.innerHTML = '';
    todos.forEach(todo => {
      const li = document.createElement('li');
      li.dataset.id = todo.id;  // 保存待办事项的 ID
      li.contentEditable = 'true';  // 使 li 可编辑
      li.textContent = todo.title;
      if (todo.completed) {
        li.classList.add('completed');
      }

      // 编辑完成按钮
      const completeButton = document.createElement('button');
      completeButton.textContent = 'Complete';
      completeButton.addEventListener('click', () => completeTodo(todo.id));

      // 删除按钮
      const deleteButton = document.createElement('button');
      deleteButton.textContent = 'Delete';
      deleteButton.addEventListener('click', () => deleteTodo(todo.id));

      // 将按钮添加到 li 中
      li.appendChild(completeButton);
      li.appendChild(deleteButton);

      // 将 li 添加到 ul 中
      todoList.appendChild(li);
    });
    addClearAllButton(); // 添加全部删除按钮
  };

  // 添加待办事项
  document.getElementById('addTodoForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const newTodo = document.getElementById('newTodo').value.trim();

    if (newTodo) {
      const token = localStorage.getItem('token');
      const response = await fetch(`${baseUrl}/todos`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ title: newTodo })
      });
      const result = await response.json();
      if (response.ok) {
        const newLi = document.createElement('li');
        newLi.textContent = newTodo;
        newLi.contentEditable = 'true';
        const deleteButton = document.createElement('button');
        deleteButton.textContent = '删除';
        deleteButton.addEventListener('click', () => {
          deleteTodo(result.id);
        });
        newLi.appendChild(deleteButton);
        document.getElementById('todoList').appendChild(newLi);
        document.getElementById('newTodo').value = '';
      } else {
        alert('Failed to add todo');
      }
    } else {
      alert('请输入有效的待办事项内容');
    }
  });

  // 删除待办事项
  const deleteTodo = async (id) => {
    const token = localStorage.getItem('token');
    const response = await fetch(`${baseUrl}/todos/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` }
    });
    if (response.ok) {
      getTodos();  // 刷新待办事项列表
    } else {
      alert('Failed to delete todo');
    }
  };

  // 完成待办事项
  const completeTodo = async (id) => {
    const token = localStorage.getItem('token');
    const response = await fetch(`${baseUrl}/todos/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ completed: true })
    });
    if (response.ok) {
      getTodos();  // 刷新待办事项列表
    } else {
      alert('Failed to complete todo');
    }
  };

  // 监听 li 的编辑事件
  document.getElementById('todoList').addEventListener('input', async (e) => {
    if (e.target.tagName.toLowerCase() === 'li') {
      const id = e.target.dataset.id;
      const newTitle = e.target.textContent.trim();
      if (newTitle) {
        const token = localStorage.getItem('token');
        const response = await fetch(`${baseUrl}/todos/${id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
          body: JSON.stringify({ title: newTitle })
        });
        if (!response.ok) {
          alert('Failed to update todo');
        }
      } else {
        e.target.textContent = 'Empty';
      }
    }
  });

  // 添加全部删除按钮
  const addClearAllButton = () => {
    const clearAllButton = document.createElement('button');
    clearAllButton.textContent = 'Clear All';
    clearAllButton.style.marginTop = '10px';
    clearAllButton.addEventListener('click', () => {
      const token = localStorage.getItem('token');
      fetch(`${baseUrl}/todos`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` }
      }).then(() => {
        getTodos(); // 刷新待办事项列表
      });
    });
    document.getElementById('todoList').parentNode.insertBefore(clearAllButton, document.getElementById('todoList'));
  };

  // 初始化
  const token = localStorage.getItem('token');
  if (token) {
    getTodos();
  } else {
    window.location.href = 'login.html';
  }
});